package Demo5;

public class ThreadState {
    public static void main(String[] args) throws InterruptedException{
        // 创建一个线程
        Thread thread = new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try{
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            System.out.println("线程结束");
        });

        // 观察线程的状态
        Thread.State state = thread.getState();
        System.out.println(state); // new

        // 启动线程
        thread.start(); // 启动线程
        state = thread.getState();
        System.out.println(state); // run

        // 只要线程不终止，就一直在输出状态
        while (state != Thread.State.TERMINATED){
            Thread.sleep(100);
            state = thread.getState(); //更新线程的状态
            System.out.println(state); // 输出线程的状态
        }

        // 再次启动结束的线程 会报错
//        thread.start();
    }
}
